import Vue from 'vue'
import Vuex from 'vuex'
import { get_song_detail, get_song_lyric } from "../api/comment";
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    song_info: {
      song_artists: [],
    },
    playPause: false,
    audio_info: {
      auto_duration: 1,
      auto_currentTime: 0,
    },
    //当前播放列表
    play_list: [],
    //当前播放歌曲的下标(第几首)
    song_idx: 0,
    songlyric: [],
    songlyric_currentTime: [],
  },
  mutations: {
    //获取状态值
    changeState(state, is_playing) {
      state.playPause = is_playing;
    },
    //获取播放歌曲详细信息
    changeSong_info(state, info) {
      state.song_info = info;
    },
    //改变播放，暂停状态值
    changeplayPause(state) {
      state.playPause = !state.playPause;
    },
    //获取audio实例的信息
    changeAudio_info(state, info) {
      state.audio_info = info;
    },
    //获取当前播放列表
    set_play_list(state, list) {
      state.play_list = list;
    },
    //改变当前歌曲对应下标
    change_idx(state, idx) {
      state.song_idx = idx;
      console.log(idx)
    },

    //获取当前歌曲歌词
    get_songlyric(state, songlyric) {
      state.songlyric = songlyric;
    },
    //获取当前歌曲对应时间
    get_songlyric_currentTime(state, songlyric_currentTime) {
      state.songlyric_currentTime = songlyric_currentTime;
    },

  },
  actions: {
    async get_song_detail(context, id) {
      get_song_detail(id).then(song_detail => {
        let current_song = song_detail.data.songs[0];
        let song_info = {
          song_album: current_song.al.name,
          song_artists: current_song.ar,
          id: current_song.id,
          song_pic: current_song.al.picUrl,
          song_name: current_song.name,
        };
        // console.log(song_info);
        // 将当前音频的相关信息存至 store, 歌名 ar id
        // 注: 点击播放时, 会将播放列表切换至当前歌曲的所在歌单, 方便后面做上一首,下一首的切换;
        context.commit("changeSong_info", song_info);
      });

      //获取当前歌曲歌词
      get_song_lyric(id).then(data => {
        //接收数据
        let song_lyric = data.data.lrc.lyric.split("\n");
        //把数据转为 [[xxx,xxx],[xxx,xxx]]格式
        let newSong_lyric = song_lyric.map(el => {
          return el.split("]")
        })
        //取出时间戳并且转换
        let time = newSong_lyric.slice(0, newSong_lyric.length - 1).map(el => {
          //不接受空值
          return el[0].slice(1)
        })
        //处理数据，转化成秒
        let currentTime = time.map(el => {
          let min = parseInt(el.substr(0, 2)) * 60;
          let second = parseInt(el.slice(3))
          return min + second;
        })
        //把进行时间传入仓库
        context.commit("get_songlyric_currentTime", currentTime);
        //取出歌词片段
        let lyric = newSong_lyric.slice(0, newSong_lyric.length - 1).map(el => {
          return el[1]
        })
        //把歌词传入仓库
        context.commit("get_songlyric", lyric);
      });

    }
  },
  modules: {
  }
})
